import axios from "axios";
import { toast } from "./toast";
import  router  from "../router/index";
console.log(router.currentRoute);
const service = axios.create({
    baseURL: 'http://192.168.137.1:3000',
    timeout: 5000,
})
// 请求拦截器
service.interceptors.request.use(
    config => {
        // 设置header
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'

        // 让每个请求携带自定义token 
        if (localStorage.getItem('token')) {
            // header添加token
            config.headers["Authorization"] = localStorage.getItem('token');
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)

// // 响应拦截器
service.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        console.log(error.response);
        if(error.response.status === 401) {
            toast('fail', error.response.data.error, 500)
            console.log(router.currentRoute);
            router.push({path:'/login'})
            localStorage.clear()

            return Promise.reject(error.response.data.error)
        }
        return error.response
    }
)

export default service